package com.jiuyou.storeController.storeUser;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.domain.model.LoginStoreUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.aes.AESCipher;
import com.ruoyi.common.utils.img.ImgUtil;
import com.ruoyi.common.utils.tencentCos.CosAppendObject;
import com.ruoyi.common.utils.tencentCos.CosConstants;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.StoreUserTokenService;
import com.ruoyi.memberSer.domain.MemberSer;
import com.ruoyi.memberSer.service.IMemberSerService;
import com.ruoyi.store.service.IStoreUserRoleService;
import com.ruoyi.storeUser.service.IStoreUserService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.AES;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengliang
 * @date 2021/5/20
 **/
@RestController
@RequestMapping("/store/storeUser")
public class StoreUserStoreController extends StoreBaseController {
    @Autowired
    private IStoreUserService storeUserService;

    @Autowired
    private StoreUserTokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IMemberSerService memberSerService;
    @Autowired
    private IStoreUserRoleService roleService;
    /**
     * 是否显示关注公众号
     * @return
     * @throws Exception
     */
    @RequestMapping("/showFollowSer")
    public AjaxResult showFollowSer() {
        JSONObject jsonObject=new JSONObject();
        Long storeUserId= getLoginStoreUserId();
        String showFlag="N";
        if(null!=storeUserId){
            StoreUser storeUser=  storeUserService.selectStoreUserById(storeUserId);
            MemberSer memberSer= memberSerService.selectMemberSerByUinonId(storeUser.getUnionId());
            if(null==memberSer||(memberSer.getSubscribe().compareTo(0L)==0)){
                showFlag="Y";
            }
        }else{
            AjaxResult.unLogin();
        }
        jsonObject.put("showFlag",showFlag);
        return AjaxResult.success(jsonObject);
    }
    /**
     * 进来获取此人的OpenId回传
     */
    @RequestMapping("/getOpenId")
    public Map getOpenId(String code,String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);
        StoreUser exist=null;
        String unionid=null;
        if(!StringUtils.isEmpty(openId)){
            //有openid已经授权过
            exist= storeUserService.selectStoreUserByOpenId(openId);
        }
        if(null==exist){
            //手机号注册方式
            String content = storeUserService.converWechatOpenId(code);
            JSONObject jsonObject = JSON.parseObject(content);
            if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
                throw new Exception();
            }
            openId = jsonObject.getString("openid");
            exist= storeUserService.selectStoreUserByOpenId(openId);
            unionid=jsonObject.getString("unionid");
        }
        if(null != exist){
            String token = tokenService.createToken(new LoginStoreUser(exist));
            map.put("success",true);
            map.put("member",exist);
            map.put("exist",true);
            map.put("token",token);
            map.put("openId",openId);
            return map;
        }
        StoreUser member = new StoreUser();
        member.setOpenId(openId);
        member.setNickName("陌生用户");
        member.setUnionId(unionid);
        storeUserService.insertStoreUser(member);
        StoreUser regist = storeUserService.selectStoreUserById(member.getId());
        String token = tokenService.createToken(new LoginStoreUser(regist));
        map.put("member",regist);
        map.put("token",token);
        map.put("success",true);
        map.put("openId",openId);
        return map;
    }

    /**
     * 通过手机和密码登录
     * */
    @RequestMapping("/loginByUserPwd")

    public AjaxResult loginByUserPwd(String phone,String password,String userType) throws Exception {
        if(phone == null){
            return AjaxResult.error("手机号不能为空");
        }
        if(password == null){
            return AjaxResult.error("密码不能为空");
        }
        if (userType == null){
            return AjaxResult.error("类型不能为空");
        }
        StoreUser storeUser = new StoreUser();
        storeUser.setPhone(phone);
        storeUser.setUserType(userType);
        List<StoreUser> registList = storeUserService.selectStoreUserList(storeUser);
        if(registList.size() == 0){
            return AjaxResult.error("未查询到此用户");
        }
        String pwd = registList.get(0).getPassword();

        String random = "818W38q62e6OcC87";
        byte[] aesKey = random.getBytes();
        String decryptText = AESCipher.decrypt(aesKey,pwd );
        if(!decryptText.equals(password)){
            return AjaxResult.error("密码错误");
        }
        String token = tokenService.createToken(new LoginStoreUser(registList.get(0)));

        JSONObject jso=new JSONObject();
        jso.put("member",registList.get(0));
        jso.put("token",token);
        return AjaxResult.success(jso);
    }
    /**
     * 进来获取此人的OpenId回传
     */
  /*  @RequestMapping("/auto-login")
    public Map autoLogin(String openId) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);

        StoreUser m = new StoreUser();
        m.setOpenId(openId);
        List<StoreUser> members = storeUserService.selectStoreUserList(m);
        map.put("success",true);
        if(members.size()>0){
            StoreUser member = members.get(0);
            String token = tokenService.createToken(new LoginStoreUser(member));
            map.put("member",member);
            map.put("token",token);
            map.put("exist",true);
        }
        return map;
    }*/
    /**
     * 检测当前用户token是否过期
     */
   /* @RequestMapping("/check-login")
    public Map<String,Object> checkLogin(String openId ,String code) {
        Map map = new LinkedHashMap(3);
        map.put("online",false);
        map.put("regist",false);
        LoginMember loginUser = tokenService.getLoginMember();

        if(loginUser != null){
            tokenService.verifyToken(loginUser);
            map.put("online",true);
            map.put("regist",true);
            return map;
        }

        Member member = memberService.selectMemberByOpenId(openId);
        if(member != null){
            map.put("online",false);
            map.put("regist",true);
            map.put("memeber",member);
        }


        return map;

    }*/




    /**
     * 进来获取此人的OpenId回传
     */
    /*@RequestMapping("/register")
    public Map register(String encryptedData,String iv, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("exist",false);


        String content = storeUserService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        cn.hutool.json.JSONObject phoneJson = JSONUtil.parseObj(phoneStr);
        //没有区号的手机号
        if(phoneJson.get("purePhoneNumber") == null){
            throw new CustomException("注册失败");
        }
        map.put("phone",phoneJson.get("purePhoneNumber").toString());
        StoreUser m = new StoreUser();
        m.setOpenId(jsonObject.getString("openid"));

        //先根据openId看看有没有此人
//        List<Member> exist = memberService.selectMemberList(m);
        StoreUser exist = storeUserService.selectStoreUserByOpenIdOrPhone(jsonObject.getString("openid"),phoneJson.getStr("purePhoneNumber"));
        if(exist!=null){
            map.put("exist",true);
            exist.setOpenId(jsonObject.getString("openid"));
            storeUserService.updateStoreUser(exist);
            String token = tokenService.createToken(new LoginStoreUser(exist));
            map.put("member",exist);
            map.put("token",token);
            return map;
        }
        m.setPhone(phoneJson.get("purePhoneNumber").toString());

        storeUserService.insertStoreUser(m);
        List<StoreUser> members = storeUserService.selectStoreUserList(m);
        if(members.size()>0){
            StoreUser member = members.get(0);
            String token = tokenService.createToken(new LoginStoreUser(member));
            map.put("member",member);
            map.put("token",token);
            map.put("success",true);
        }
        return map;
    }*/


    @RequestMapping("/flushPhone")
    public AjaxResult flushPhone(String encryptedData,String iv, String code) {
        //微信
        String content = storeUserService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            return AjaxResult.error("获取失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        JSONObject phoneJson= (JSONObject) JSONObject.parse(phoneStr);
        String  PhoneNumber =phoneJson.getString("purePhoneNumber");
        System.out.println("tangyin");
        System.out.println(PhoneNumber);
        if( PhoneNumber== null){
            return AjaxResult.error("获取失败");
        }
        Long storeUserId= getLoginStoreUserId();
        StoreUser storeUserQuery=new StoreUser();
        storeUserQuery.setPhone(PhoneNumber);
        storeUserQuery.getParams().put("idueq",storeUserId);
//        List list=storeUserService.selectStoreUserList(storeUserQuery);
//       if(list.size()>0){
//           //这个手机号其他人用了
//           return AjaxResult.error("操作失败，该手机号已绑定其它微信");
//       }

        StoreUser storeUserUpdate=new StoreUser();
        storeUserUpdate.setId(storeUserId);
        storeUserUpdate.setPhone(PhoneNumber);
        storeUserService.updateStoreUser(storeUserUpdate);
        StoreUser storeUser= storeUserService.selectStoreUserById(storeUserId);
        //更新权限
        roleService.updateUserIdByPhone(storeUserId,PhoneNumber);
        String token = tokenService.createToken(new LoginStoreUser(storeUser));
        JSONObject jso=new JSONObject();
        jso.put("token",token);
        jso.put("member",storeUser);
        return AjaxResult.success(jso);
    }
    //获取用户手机号
    @RequestMapping("/getPhone")
    public AjaxResult getPhone(String encryptedData,String iv, String code) {
        //微信
        String content = storeUserService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            return AjaxResult.error("获取失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        JSONObject phoneJson= (JSONObject) JSONObject.parse(phoneStr);
        String  PhoneNumber =phoneJson.getString("purePhoneNumber");
        if( PhoneNumber== null){
            return AjaxResult.error("获取失败");
        }

        return AjaxResult.success(PhoneNumber);
    }
    //刷新用户手机号
   /* @RequestMapping("/flushPhone")
    public AjaxResult flushPhone(String encryptedData,String iv, String code) {
        String content = storeUserService.converWechatOpenId(code);
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject.get("session_key") == null || jsonObject.get("openid") == null) {
            throw new CustomException("注册失败");
        }
        String session_key = jsonObject.get("session_key").toString();
        String phoneStr = AES.wxDecrypt(encryptedData, session_key, iv);
        JSONObject phoneJson= (JSONObject) JSONObject.parse(phoneStr);
        String  PhoneNumber =phoneJson.getString("purePhoneNumber");
        //没有区号的手机号
        if( PhoneNumber== null){
            return AjaxResult.error("获取失败");
        }
        //默认此人一定存在
        //根据openID查找
        StoreUser member = storeUserService.selectStoreUserByOpenId(jsonObject.getString("openid"));
        if(null == member){
            throw new ServiceException("用户不存在");
        }
        member.setPhone(phoneJson.get("purePhoneNumber").toString());
        map.put("exist",true);
        storeUserService.updateStoreUser(member);
        String token = tokenService.createToken(new LoginStoreUser(member));
        map.put("member",member);
        map.put("token",token);
        map.put("success",true);
        return map;
    }
*/

    /**
     * 修改用户基本信息
     */
    @PostMapping("/update/basic/info")
    public AjaxResult updateBasicInfo(@RequestBody Map<String, Object> paramMap) {
        String headImgUrl = String.valueOf(paramMap.get("headImgUrl"));  //用户头像
        String nickName = StringUtils.toStringIfNull(paramMap.get("nickName"));  //昵称
//        Integer gender = Integer.valueOf(String.valueOf(paramMap.get("gender")));  //性别
        Long loginMemberId = tokenService.getLoginStoreUserId();

        String fileName = DateUtils.dateTime() +"-"+IdUtils.fastUUID()+"-"+DigestUtils.md5Hex(String.valueOf(loginMemberId)) + ".jpg"; //文件名
        // 上传文件路径
        String uploadDir = RuoYiConfig.getUploadPath();
        String filePath="/headImg";
        String fileAbsolutePath = uploadDir + filePath +"/"+ fileName;
        try {

            // 读取头像图片
            BufferedImage bufferedImage = ImgUtil.loadImageUrl(headImgUrl, false);
            // 输出
            File file = new File(fileAbsolutePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            ImageIO.write(bufferedImage, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headImg = serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/upload/headImg/" + fileName;
        if(DicConstants.SYS_Y.getCode().equals(configService.selectConfigByKey("cententOSS"))){
            Map<String, String> map = new HashMap<>(4);
            map.put("secretKey",configService.selectConfigByKey("secretKey"));
            map.put("secretId",configService.selectConfigByKey("secretId"));
            map.put("area",configService.selectConfigByKey("area"));
            map.put("bucketName",configService.selectConfigByKey("bucketName"));
            //开启腾讯oss
            headImg= CosAppendObject.AppendObjectFromLocal(map,fileName,fileAbsolutePath,"upload/"+filePath);
        }
        StoreUser member = new StoreUser();
        member.setId(loginMemberId);
        member.setHeadImg(headImg);
        member.setNickName(nickName);
        storeUserService.updateStoreUser(member);
        LoginStoreUser loginMember = tokenService.getLoginStoreUser();
        loginMember.setStoreUser(member);
        tokenService.setloginMember(loginMember);


        return AjaxResult.success(member);
    }


   /* @RequestMapping("/reload")
    public Member reload(){
        try {
            LoginMember loginMember = tokenService.getLoginMember();
            if(loginMember == null){
                return null;
            }
            return memberService.selectMemberById(loginMember.getMember().getId());
        }catch (Exception e){
            return null;
        }

    }
    @RequestMapping("/loginout")
    public void loginout(){
        Long id = tokenService.getLoginMemberId();
        memberService.loginOut(id);
        tokenService.loginOut();
    }
*/
    @RequestMapping("/remove-token")
    public void removeToken(HttpServletRequest request){
        tokenService.delLoginStoreUser(request);
    }

    /**
     * 获取最新用户信息
     * @return
     */
    @PostMapping("/getMember")
    public AjaxResult getMember() {
        Long loginMemberId = tokenService.getLoginStoreUserId();
        if(null==loginMemberId){
            return AjaxResult.error("获取失败01");
        }
        StoreUser memberData=storeUserService.selectStoreUserById(loginMemberId);
        return AjaxResult.success(memberData);
    }
}

